package com.shanu.apps.details;

import java.util.ArrayList;
import java.util.HashMap;

import mapviewballoons.example.custom.CustomBalloonOverlayView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.apps.essentials.ConsumeWebService;
import com.apps.realtyportal.HomeActivity;
import com.apps.realtyportal.LoginActivity;
import com.apps.realtyportal.MultipleSearching2;
import com.apps.realtyportal.R;
import com.forimageandlist.ImageLoader;
import com.jason.apps.alert.AlertDialogFragment;
import com.jason.apps.notify.GMailSender;

@SuppressWarnings("deprecation")
public class Detalye extends SherlockFragmentActivity implements
		AdapterView.OnItemClickListener, ViewSwitcher.ViewFactory {

	int curIndex = 0;
	int downX, upX;

	private ImageView call;
	private ImageView like;
	private ImageView main_pic;
	private TextView fav;
	private TextView title;
	private TextView price;
	private TextView type;
	private TextView description;
	private TextView agent;
	private TextView address;
	Gallery g;
	String mobilenumber;
	String email;
	String name;

	private LinearLayout l;
	private LinearLayout lcall;

	ConsumeWebService consume;
	public final static String ARG_POSITION = "position";
	public static final int DASHBOARD = 1;
	int mCurrentPosition = -1;
	SherlockFragmentActivity fa;
	public ImageLoader imageLoader;
	int prop_id = 0;
	int property_id = 0;

	Context appContext;
	HashMap<String, String> map;
	Bitmap[] bitmapimage;
	static ArrayList<String> images;
	private ActionBar actionbar;
	String pname;
	String add;
	String pprice; 
	String aname;
	String con;
	String des;
	int id=0; 
	String ttype;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detalye);
	

		actionbar = getSupportActionBar();
		actionbar.setDisplayHomeAsUpEnabled(true);
		actionbar.setDisplayShowTitleEnabled(false);
		actionbar.setLogo(R.drawable.logo3);
		like = (ImageView) this.findViewById(R.id.ddetail_favorites);
		fav = (TextView) this.findViewById(R.id.ddetail_textfavorites);
		main_pic = (ImageView) this.findViewById(R.id.dimageView1);
		title = (TextView) this.findViewById(R.id.ddetail_title);
		price = (TextView) this.findViewById(R.id.ddetail_price);
		type = (TextView) this.findViewById(R.id.ddetail_type);
		agent = (TextView) this.findViewById(R.id.ddetail_agent);
		address = (TextView) this.findViewById(R.id.ddetail_address);
		call = (ImageView) this.findViewById(R.id.ddetail_call);
		description = (TextView) this.findViewById(R.id.ddetail_description);
		l = (LinearLayout) this.findViewById(R.id.layout_favorites);
		lcall = (LinearLayout) this.findViewById(R.id.layout_call);

		imageLoader = new ImageLoader(this);
		
		Bundle extras = getIntent().getExtras();

		if (extras != null) {
			title.setText(extras.getString("propertyname"));
			description.setText(extras.getString("propertydescription"));
			price.setText("Price: "+"Php"+extras.getString("propertyprice"));
			address.setText("Address: "+extras.getString("propertyaddress"));
			type.setText("Type: " +extras.getString("propertytype"));
			agent.setText("Agent: "+ extras.getString("propertyagent"));
			con=("Contact: "+extras.getString("contact"));
			id=Integer.parseInt(extras.getString("propertyid"));
		}
//		new LoadPropertyFromBalloon().execute();
		// showGallery(mCurrentPosition);
		call.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(Intent.ACTION_DIAL);
				intent.setData(Uri.parse("tel:" + mobilenumber));
				startActivity(intent);
			}
		});
		like.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				new Add().execute();
			}
		});
		fav.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				new Add().execute();
			}
		});

		g = (Gallery) this.findViewById(R.id.dgallery);
		g.setOnItemClickListener(this);

		// if(LoginActivity.PersonType.equals("Agent")){
		// l.setVisibility(View.GONE);
		// lcall.setVisibility(View.GONE);
		// }
		
		/*//setText(pname, add, pprice, aname,
				con, des, id, ttype);*/
	}

	@Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		 menu.add(0, DASHBOARD, 0, "Logout")
		 .setTitle("Favorites")
		 .setIcon(R.drawable.favorites)
		 .setShowAsAction(
		 MenuItem.SHOW_AS_ACTION_IF_ROOM);
		
		
		
		 return super.onCreateOptionsMenu(menu);

		/*SubMenu subMenu = menu.addSubMenu("Options");

		// subMenu.add("Logout").setIcon(R.drawable.logouticon);
		// subMenu.add("Go to Profile").setIcon(R.drawable.profile1);

		subMenu.add(0, 10, Menu.NONE, "Logout").setIcon(R.drawable.logouticon);
		subMenu.add(0, 15, Menu.NONE, "Back to Dashboard").setIcon(
				R.drawable.profile);

		MenuItem subMenu1Item = subMenu.getItem();
		subMenu1Item.setIcon(R.drawable.ic_action_overflow);
		subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

		return super.onCreateOptionsMenu(menu);*/
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			Intent intent = new Intent(this, HomeActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			startActivity(intent);

		case DASHBOARD:
			// finish();
			startActivity(new Intent(getApplicationContext(),
					HomeActivity.class));
			HomeActivity.islogin=false;
		

		}
		return super.onOptionsItemSelected(item);
	}

	public void setText(String pname, String add, String pprice, String aname,
			String con, String des, int id, String ttype) {
		title.setText(pname);
		address.setText(add);
		price.setText(pprice);
		type.setText(ttype);
		agent.setText(aname);
		mobilenumber = con;
		description.setText(des);
		prop_id = id;

	}

	public void showGallery(int id) {
		/*
		 * HashMap<String, String> map = AllProperty.mylist.get(id);
		 * 
		 * String
		 * data=consume.getAmmenities(Integer.parseInt(map.get(AllProperty
		 * .KEY_ID))); try { JSONArray array = new JSONArray(data);
		 * 
		 * for (int i = 0; i < array.length(); i++) { JSONObject e =
		 * array.getJSONObject(i); images.add(e.getString("url")); }
		 * 
		 * } catch (JSONException e) { Log.e("log_tag", "Error parsing data " +
		 * e.toString()+"diri jud"); }finally{
		 * 
		 * }
		 */
		g.setAdapter(new ImageAdapter(this));
	}

	public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {

		Intent i = new Intent(this, ViewImage.class);
		startActivity(i);

	}

	public View makeView() {
		ImageView i = new ImageView(this);
		i.setScaleType(ImageView.ScaleType.FIT_CENTER);
		i.setLayoutParams(new ImageSwitcher.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

		return i;
	}

	private ImageSwitcher mSwitcher;

	public class ImageAdapter extends BaseAdapter {
		public ImageAdapter(Context c) {
			mContext = c;
		}

		public int getCount() {
			return images.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView i = new ImageView(mContext);

			imageLoader.DisplayImage(images.get(position), i);
			Log.e("Url Here:", images.get(position));
			// i.setImageResource(mThumbIds[position]);
			i.setAdjustViewBounds(true);
			i.setLayoutParams(new Gallery.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			// i.setBackgroundResource(R.drawable.picture_frame);
			return i;
		}

		private Context mContext;

	}

	public class loadImage extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub

			String data = consume.getAmmenities(id);
			try {
				JSONArray array = new JSONArray(data);

				for (int i = 0; i < array.length(); i++) {
					JSONObject e = array.getJSONObject(i);
					images.add(e.getString("url"));
				}

			} catch (JSONException e) {
				Log.e("log_tag", "Error parsing data " + e.toString()
						+ "diri jud");
			} finally {

			}
			return null;
		}

		protected void onPostExecute(Void result) {
			g.setAdapter(new ImageAdapter(Detalye.this));
		}

	}

	public class Add extends AsyncTask<Void, Void, Void> {

		private ProgressDialog dialog;
		boolean results = false;
		int person_id = LoginActivity.id;

		protected void onPreExecute() {
			dialog = new ProgressDialog(Detalye.this);
			dialog.setMessage("Loading...");
			dialog.show();
		}

		protected Void doInBackground(final Void... unused) {

			try {
				results = consume.SaveLead(id, CustomBalloonOverlayView.panoramaId);

				if (results) {
					try {
						GMailSender sender = new GMailSender(
								"jesonenerez@gmail.com", "jesonenerez");
						sender.sendMail("Favorites",
								"Somebody is interested with this property of yours: "
										+ name, "jesonenerez@gmail.com", email);
						Log.e("Message", "Na sent bai");
					} catch (Exception e) {
						Log.e("SendMail", e.getMessage(), e);
					}
					FragmentManager fm = getSupportFragmentManager();
					AlertDialogFragment alert = new AlertDialogFragment();
					/** Opening the dialog window */
					alert.show(fm, "Alert_Dialog");

				}
				System.out.println(prop_id + "-" + person_id);

			} catch (Exception e) {
				Log.e("", "wala jud ma add", e);
			}

			return null;
		}

		protected void onPostExecute(Void result) {

			if (this.dialog != null) {
				this.dialog.dismiss();
			}
		}
	}
	 public class LoadPropertyFromBalloon extends AsyncTask<Void, Void, Void> {

		    ProgressDialog dialog;
		    boolean results;
		    String propertyName;
		    String paddress;
		    String propertyType;
		    String agentName;
		    String pmobilenumber;
		    String pprice;
		    String data;
		    String pdescription;
		    String pId;
		    String pimage;
		    String pemail;
		    
		    protected void onPreExecute() {
		    	dialog = new ProgressDialog(Detalye.this);
		            dialog.setMessage("Loading...");
		            dialog.show();
		    }

		    protected Void doInBackground(final Void... unused) {

				try {
					data=consume.getAllPropertyById(CustomBalloonOverlayView.panoramaId);
			
					JSONArray array = new JSONArray(data);
					
					for (int i = 0; i <= array.length(); i++) {
						JSONObject e = array.getJSONObject(i);
						
						propertyName=e.getString("property_name");
						pdescription=e.getString("property_description");
						paddress=e.getString("address");
						pprice=e.getString("price");
						propertyType=e.getString("type");
						pmobilenumber=e.getString("mobile");
						pimage=e.getString("main_image");
						pemail=e.getString("email_address");
						agentName=e.getString("firstname")+" "+e.getString("lastname");
					}
					
				} catch (Exception e) {
					Log.e("","",e);
					//Toast.makeText(getApplicationContext(), "No Panorama Image Found!", Toast.LENGTH_LONG).show();
				}
		   
		        return null; 
		    }
		    
		    protected void onPostExecute(Void result) {
		    	
		    	if(data!=null){
		    		
		    		title.setText("Name: "+ propertyName);
		    		price.setText("Price: "+pprice);
		    		type.setText("Type: "+propertyType);
		    		description.setText(pdescription);
		    		
		    		address.setText("Address:"+paddress);
		    		agent.setText("Agent: " + agentName);
		    		prop_id=Integer.parseInt("");
		    		mobilenumber=pmobilenumber;
		    		email=(pemail);
		    	    imageLoader.DisplayImage(pimage, main_pic);
		    	}
		    	if (this.dialog!=null) {
		            this.dialog.dismiss();
		            }  
		}
	    }

	/*
	 * public class DisableField extends AsyncTask<Void, Void, Void> {
	 * 
	 * protected void onPreExecute() {
	 * 
	 * } protected Void doInBackground(final Void... unused) {
	 * 
	 * 
	 * return null; } protected void onPostExecute(Void result) {
	 * 
	 * } }
	 */

}